<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require("base.php");
require("constants.php"); 

/**
*  Added By ZhouHuan, 2012.9.23
*/
class User extends Base {
	
	function __construct() {
        session_start();
		$this->pdf_dir = PDF_DIR; 
		$this->zip_dir = ZIP_DIR;  
		$this->packed_zip_name = PACKED_ZIP_NAME;
		parent::__construct();
	}
	
	/**
	 * 首页 
	 */
	public function index()
	{    
        $this->config->load('my_options', TRUE);  
        $countries = $this->db->query("select * from visa_countries where CHAR_LENGTH(cn_name)=2 order by visa_count desc")->result_array();
        $data = array(
            'countries'=>$countries,
            'visa_purpose_array' => $this->config->item('visa_purpose', 'my_options')   
        );
		$this->load->view('user_index', $data);
	}
	
        
    /**
     * 显示登录验证码
     */
    public function authcode() {
        header("Cache-Control: no-cache, no-store, max-age=0"); 
        header("Pragma: no-cache");
        header("Expires: 0");    
        $params = array(
            "pos_x"=>80,
            "pos_y"=>22,
            "bg_shape"=>'*',
            "shape_num"=>25,
            "case_sensitive"=>false
        );
        $this->load->library("authcode", $params);
        $this->authcode->show();
        $code = $this->authcode->getCode();  
        $_SESSION['trip_auth_code'] = $code;  
    }
	
	/**
	 * 登录
	 */
	public function login(){
		$this->load->view('user_login');
	}
    
    /**
     * 注销
     */
    public function logout(){
        foreach($_SESSION as $k=>$v) {
           unset($_SESSION[$k]);     
        }
        redirect("user");
    }
	
	/**
	 * 处理登录
	 */
	public function do_login(){
        if(strtolower($_POST['ac']) != $_SESSION['trip_auth_code']) {
            echo "ac_incorrect";
            return;

        } else if($this->has_sql_inject($_POST["uid"], $_POST["pwd"])){
            $this->log_info('test');  
            echo "sorry";
            
        } else {
            $sql = "select * from visa_users where user_name='".$_POST["uid"]."' and login_pass='".md5($_POST["pwd"])."'";
            $this->log_info($sql);
            $query = $this->db->query($sql);
            if($query->num_rows() > 0) { 
                $row = $query->row();    
                if(intval($row->enabled) == 0) {
                    echo "disabled";  // 用户已失效
                    exit;
                }
                $_SESSION['user_name'] = $_POST['uid'];
                $_SESSION['user_id'] = $row->id;
                $_SESSION['user_mail'] = $row->email;  
                $this->db->where('id', $row->id);
                $this->db->update("visa_users", array('last_login_time'=>date("Y-m-d H:i:s")));
                $this->write_operate_log("登录成功");
                echo "ok";
            } else {
                $this->write_operate_log("登录失败[".$_POST["uid"]."]");
                echo "sorry";
            } 
        }
	}
	
	/**
	 * 注册
	 */
	public function register(){
		$this->load->view('user_register');
	}
	
	/**
	 * 处理注册
	 */
	public function do_register(){
        $_POST['login_pass'] =  md5($_POST['login_pass']); 
        $_POST['register_time'] =  $this->dt();
        $this->db->insert("visa_users", $_POST);
		echo "ok";
	}
    
    /**
    * 检测用户名是否存在
    */
    public function check_user_name($n){
        if($this->db->query("select id from visa_users where user_name='$n'")->num_rows() > 0) {
           echo "yes"; 
        } else {
           echo "no";   
        }
    }
    
    /**
     * 办理签证入口
     */
    public function start(){
        $this->load->view('user_start');
    }  
    
    /**
     * 显示国家选择
     */
    public function countries($card_id=NULL){    
        if( ! $this->user_is_logined() ) {
            $params = array();
            foreach($_GET as $k=>$v) {
                $params[] = $k.'='.$v;
            }   
            $url = 'user/countries';
            if(count($params) > 0 ) $url .= '?'.implode("&", $params);        
            $_SESSION['before_login_page'] = $url;
            redirect('user/login');
        }
        $_SESSION['current_card_id'] =  $card_id; // 保存当前的card_id参数，用于国家选择的回退修改
        $this->config->load('my_options', TRUE);    
        $countries = $this->db->query("select * from visa_countries order by visa_count desc, char_length(cn_name)")->result_array();
        $provinces = $this->db->query("select * from visa_province order by id")->result_array(); 
        $data = array(
            'countries'=>$countries,
            'provinces'=>$provinces,    
            'visa_type_array' => $this->config->item('visa_type', 'my_options'), 
            'visa_purpose_array' => $this->config->item('visa_purpose', 'my_options') 
        );
        $this->load->view('user_countries',$data); 
    }

    /**
    * 国家快速搜索输入框
    */
    public function quick_search_country() {
        $sql = "select * from visa_countries where 1=1 ";
        if(isset($_GET['q'])) { // for autocomplete
            $sql .= " and (cn_name like '".$_GET['q']."%' or short_name like '".$_GET['q']."%')";
        }
        $sql .= " order by visa_count desc";
        $query = $this->db->query($sql);
        $arr = array();
        foreach ($query->result() as $row) {
            $arr[] = $row->id .",". $row->cn_name.','.$row->short_name.','.$row->is_schengen.','.$row->en_name;;
        }
        echo join("\n", $arr);
    }

    
    /**
    * 民族快速搜索输入框
    */
    public function quick_search_ethnic() {
        $sql = "select * from visa_ethnic where 1=1 ";
        if(isset($_GET['q'])) { // for autocomplete
            $sql .= " and (cn_name like '".$_GET['q']."%' or en_name like '".$_GET['q']."%')";
        }
        $sql .= " order by people_count desc";
        $query = $this->db->query($sql);
        $arr = array();
        foreach ($query->result() as $row) {
            $arr[] = $row->id .','. $row->cn_name.','.$row->en_name;
        }
        echo join("\n", $arr);
    }

    /**
    * 省份快速搜索输入框
    */
    public function quick_search_province() {
        $sql = "select * from visa_province where 1=1 ";
        if(isset($_GET['q'])) { // for autocomplete
            $sql .= " and (province_name like '".$_GET['q']."%' or en_name like '".$_GET['q']."%')";
        }
        $sql .= " order by en_name desc";
        $query = $this->db->query($sql);
        $arr = array();
        foreach ($query->result() as $row) {
            $arr[] = $row->id .','. $row->province_name.','.$row->en_name;
        }
        echo join("\n", $arr);
    }
    
    /**
     * 保存国家选择状态
     */
    public function save_countries($action='save'){
        if($action == 'clear') {
            unset($_SESSION['province_name']);
            unset($_SESSION['visa_type']);
            unset($_SESSION['visa_purpose']);
            unset($_SESSION['visa_type_name']);
            unset($_SESSION['visa_purpose_name']);     
            unset($_SESSION['country_ids']);
            unset($_SESSION['country_cn_names']);      
            unset($_SESSION['country_short_names']);
            unset($_SESSION['country_schengen_names']);
            unset($_SESSION['main_schengen_country']);
        } else {  
            $this->config->load('my_options', TRUE);  
            $visa_type_arr = $this->config->item('visa_type', 'my_options');
            $visa_purpose_arr = $this->config->item('visa_purpose', 'my_options');  
            $_SESSION['visa_type_name'] = $visa_type_arr[$_POST['visa_type']];  // 将两个类型中文名存入session
            $_SESSION['visa_purpose_name'] = $visa_purpose_arr[$_POST['visa_purpose']];    
            $_SESSION['province_name'] = $_POST['province_name']; 
            $_SESSION['visa_type'] = $_POST['visa_type']; 
            $_SESSION['visa_purpose'] = $_POST['visa_purpose'];  
            $_SESSION['country_ids'] = $_POST['country_ids'];
            $_SESSION['country_cn_names'] = $_POST['country_cn_names'];        
            $_SESSION['country_short_names'] = $_POST['country_short_names'];
            $_SESSION['country_schengen_names'] = $_POST['country_schengen_names'];
            $_SESSION['main_schengen_country'] = $_POST['main_schengen_country'];   
            if(isset($_SESSION['current_card_id'])) {
                unset($_POST['province_name']);  // 针对退回修改国家选择，要同步更新关联表的记录
                $_POST['update_time'] = date("Y-m-d H:i:s");
                $this->db->update("visa_user_forms", $_POST, array('card_id'=>$_SESSION['current_card_id']));
            }
        }
        echo "ok";     
    }    
    
    /**
     * 显示用户资料
     */
    public function show_info(){
        $this->check_user_logined();   
        $result = $this->db->query("select * from visa_users where id=".$_SESSION['user_id'])->row();
        $data = array('user_info'=>$result);
        $this->load->view('user_show_info', $data); 
    }    

    /**
    * 更新用户资料
    */
    public function update_info(){
        $this->db->update("visa_users", $_POST, array('id'=>$_SESSION['user_id']));
        echo "ok";
    }
    
     /**
    * 更新用户密码 
    */
    public function update_password(){
        // 需要 MD5 加密处理，所以单独分开     
        $this->db->update("visa_users", array('login_pass'=>md5($_POST['login_pass'])), array('id'=>$_SESSION['user_id']));
        echo "ok";
    }


	/**
	 * 显示历史签证记录
	 */
	public function list_forms($page=1){
        $page_size = 30;
        $start_index = ($page-1)*$page_size;
        $this->check_user_logined(); 
        $this->config->load('my_options', TRUE);   
        $condition = "1=1";
        if(isset($_GET['search_by'])) {
            if($_GET['search_by'] == "fullname") {
              $condition = "concat(surname, firstname) = '". $_GET['search_value'] ."'";     
            } else if($_GET['search_by'] == "idcard")  {
               $condition = "national_id = '". $_GET['search_value'] ."'";       
            }
        }
        $sql = "select a.*,b.surname,b.firstname,b.national_id from visa_user_forms a 
        Left Join archive_idcard b On a.card_id=b.id where a.user_id=".$_SESSION['user_id']." and $condition order by id desc limit $start_index, $page_size";
        $result = $this->db->query($sql)->result();
        $total_rows = $this->db->query("select count(0) as cnt from visa_user_forms  a 
        Left Join archive_idcard b On a.card_id=b.id where $condition and user_id=".$_SESSION['user_id'])->row()->cnt; 
        /*$this->load->library('pagination');
        $config['base_url'] = base_url().'user/list_forms';
        $config['total_rows'] = $this->db->query('select count(0) as cnt from visa_user_forms where user_id='.$_SESSION['user_id'])->row()->cnt;   
        $config['per_page'] = $page_size;
        $config['first_link'] = '首页';
        $config['last_link'] = '末页';
        $this->log_info(print_r($config, true));
        $this->pagination->initialize($config);*/
        // CI自带的 pagination 类有bug，还是用自己的;
        $this->load->library('pagelinks');
        $this->pagelinks->setRecordCount($total_rows);          
        $this->pagelinks->setPageSize($page_size); 
        $data = array( 
            'list' => $result,
            'page_links' => $this->pagelinks->show(true),  // $this->pagination->create_links(),
            'visa_type_array' => $this->config->item('visa_type', 'my_options'), 
            'visa_purpose_array' => $this->config->item('visa_purpose', 'my_options')
        );
		$this->load->view('user_list_forms', $data);    
	}
	
	/**
	 * 查看签证表单内容
	 */
	public function show_forms($card_id=NULL){
        $this->check_user_logined(); 
         if($card_id != NULL) {   // 查看历史签证记录信息时，先进行提取
            $sql = "select * from visa_user_forms where card_id=$card_id";
            $arr = $this->db->query($sql)->row_array();
            $this->config->load('my_options', TRUE);  
            $visa_type_arr = $this->config->item('visa_type', 'my_options');
            $visa_purpose_arr = $this->config->item('visa_purpose', 'my_options');  
            $_SESSION['visa_type_name'] = $visa_type_arr[$arr['visa_type']];  // 将两个类型中文名存入session
            $_SESSION['visa_purpose_name'] = $visa_purpose_arr[$arr['visa_purpose']];     
            $_SESSION['main_schengen_country'] = $arr['main_schengen_country'];
            $_SESSION['country_cn_names'] = $arr['country_cn_names'];
            $_SESSION['country_short_names'] = $arr['country_short_names'];        
            $_SESSION['country_schengen_names'] = $arr['country_schengen_names'];    
            $_SESSION['visa_type'] = $arr['visa_type'];  
            $_SESSION['visa_purpose'] = $arr['visa_purpose']; 
            $_SESSION['country_ids'] = $arr['country_ids'];
            $_SESSION['province_name'] = $arr['province_name'];  
            unset($_SESSION['current_card_id']); // 清除当前选定进行修改的记录ID   
        }
        $_SESSION['in_form_frame'] = 'yes'; // 标识在iframe框架中 
        $data = array('card_id'=>$card_id);    
        $this->load->view('user_show_forms', $data); 
	}
    
    /**
     * 删除签证表单记录
     */
    public function delete_forms($card_id=NULL){
        $this->check_user_logined(); 
        if($card_id==NULL) show_error("parameter missing");
        $sql = "delete from visa_user_forms where card_id=$card_id and user_id=".$_SESSION['user_id'];
        $this->log_info($sql);
        $this->db->simple_query($sql);
        $this->write_operate_log("删除签证记录[$card_id]");
        //$sql = "delete from archive_idcard where id=$card_id";
        //$this->db->simple_query($sql);   
        /*$sql = "SHOW TABLES"; // 删除相关表单记录    
        $result = $this->db->query($sql)->result_array();
        foreach($result as $v) {
            $table_name = array_pop($v);
            $n = explode('_', $table_name);
            if( in_array($n[0], array('order','schengen','archive')) ) {
                $this->log_info($table_name);
            }
        }*/ 
        echo "ok";
    }
    
    /**
    * 取到指定客户已填的表格id
    */
    public function get_form_ids_by_idcard($id) {
        $sql = "select fill_form from archive_idcard where id=$id";
        echo $this->db->query($sql)->row()->fill_form;
    }
    
    
    /**
    * 下载Adobe生成的pdf表格
    */
    var $pdf_dir = "";
	var $zip_dir = "";
    var $packed_zip_name = "";
    
    public function make_pdf_to_zip($card_id=NULL, $form_ids="") {
        $this->check_user_logined(); 
        if($card_id==NULL) show_error("parameter missing");
        $zip_name = $card_id."_".$this->packed_zip_name;
        $zip_file_path = $this->zip_dir . $zip_name;
        if(file_exists($zip_file_path)) {
            unlink($zip_file_path); // 删除掉已存在的zip文件
        }
        $this->load->library("zipmaker"); 
        $this->zipmaker->create_zip($this->get_pdf_file_list($card_id, $form_ids), $zip_file_path);
        $this->write_operate_log("打包签证表格[$card_id]");  
        echo "{result:'ok', file_name:'$zip_name'}";
    }
    
    /**
    *  返回指定idcard的关联pdf文件列表
    */
    private function get_pdf_file_list($card_id, $form_ids="") {
        $files = array();
        $form_ids = explode("_", $form_ids);
        $pdf_names = array(); 
        $result = $this->db->query("select pdf_name from r_table_pdf where id in (".join(",", $form_ids).")")->result();
        foreach($result as $row) {
           $pdf_names[] = $row->pdf_name; // 根据id串读取到关联的pdf文件名数组
        } 
        if ($handle = opendir($this->pdf_dir)) {
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != "..") {
                    $arr = explode("_", $file);
                    // 判断pdf文件前缀为card_id, 并且判断pdf文件在选中范围内
                    if($arr[0] == $card_id && in_array(substr($file, strpos($file,"_")+1), $pdf_names)) { 
                        $files[] = $this->pdf_dir . $file;
                    }
                }
            }
            closedir($handle);
        }
        return $files;
    }

    
    /**
    * 下载打包成Zip的pdf文件
    */
     public function download_forms($card_id=NULL) {
        $this->check_user_logined(); 
        if($card_id==NULL) show_error("parameter missing");       
        $zip_name = $card_id."_".$this->packed_zip_name;
        $zip_file_path = $this->zip_dir . $zip_name;
        ob_end_clean();
        header("Content-Type: application/force-download");
        header("Content-Transfer-Encoding: binary");
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename='.$zip_name);
        header('Content-Length: '.filesize($zip_file_path));
        error_reporting(0);
        readfile($zip_file_path);
        flush();
        ob_flush();
    }   

    
    /**
    * 下载打包成Zip的pdf文件
    */
     public function send_mail_forms($card_id=NULL) {
        $this->check_user_logined(); 
        if($card_id==NULL) show_error("parameter missing");      
        $zip_name = $card_id."_".$this->packed_zip_name;
        $file = $this->zip_dir . $zip_name;
        $boundary = uniqid(""); 
        $mimeType = "zip";
                 
        // 打开文件 
        $fp = fopen($file, "r"); 
        $read = fread($fp, filesize($file)); 
        $read = base64_encode($read); 
        //把这个长字符串切成由每行76个字符组成的小块 
        $read = chunk_split($read); 
        fclose($fp);//关闭文件

        $smtpusermail = "services@68visa.com";//SMTP服务器的用户邮箱,发送者
        $smtpemailto = $_GET['user_mail'];//发送给谁
        $mailsubject = "您的签证PDF表格文件,请查收";//邮件主题
        $mailsubject = "=?UTF-8?B?".base64_encode($mailsubject)."?="; // 处理标题乱码
        $mailtype = "HTML";//邮件格式（HTML/TXT）,TXT为文本邮件

            //有附件
           $flag = 2;
           $body = "--$boundary\r\n"; //此必须\r\n
           $body .= "Content-Type:text/html; charset=utf-8\r\n\r\n";//此必须\r\n\r\n
           $body .= "您好：<br><br>　　附件中是您的签证PDF表格文件,请查收！<br><br>　　68Visa.com\r\n"; 
           $body .= "--$boundary\r\n"; 
           $body .= "Content-type: $mimeType; name=$zip_name\r\n"; 
           $body .= "Content-disposition: attachment; filename=$zip_name\r\n"; 
           $body .= "Content-Transfer-Encoding: BASE64\r\n\r\n"; 
           $body .= "$read\r\n\r\n"; 
           $body .= "--$boundary--\r\n"; 
      
        $mailbody = $body;//邮件内容
        $cc = "";//抄送
        $bcc = "";//副收件人
        $this->load->library("smtp"); 
        $additional_headers = "";
        if($this->smtp->sendmail($flag, $boundary, $smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype,$cc,$bcc,$additional_headers)) {
           echo("<script>alert('邮件已发送成功，请查收！'); parent.hide_waiting();</script>");
        }
    } 
}

/* End of file user.php */
/* Location: ./application/controllers
r.php */
